<template>
  <div class="no-background-container">
    <!-- 搜索表单 -->
    <search-form-qvil
      v-model="queryForm"
      :affixed="true"
      :fields="searchFields"
      :inline="true"
      :loading="tableState.loading"
      :show-label="false"
      @form-change="handleFormChange"
      @reset="handleReset"
      @search="handleSearch"
    >
      <template #actions>
        <el-button type="primary" @click="handleAdd">新增{{ moduleName }}</el-button>
        <el-button type="primary" @click="openImportDialog">批量导入</el-button>
      </template>
    </search-form-qvil>

    <!-- 表格 -->
    <table-qvil
      v-model:page="queryForm.page"
      v-model:page-size="queryForm.limit"
      :border="true"
      :columns="tableState.visibleColumns"
      :data="tableState.data"
      :loading="tableState.loading"
      :show-index="true"
      :stripe="true"
      :total="tableState.pagination.total"
      @page-change="handlePageChange"
      @size-change="handleSizeChange"
    >
      <!-- 用户列 -->
      <template #column-userInfo="{ row }">
        <div>{{ row.userInfo ? row.userInfo.name : '-' }}</div>
      </template>

      <!-- 酒店列 -->
      <template #column-hotelManagementId="{ row }">
        <div>{{ getHotelName(row.hotelManagementId) }}</div>
      </template>

      <!-- 操作列 -->
      <template #column-operations="{ row }">
        <div class="operations-container">
          <el-button size="small" text type="primary" @click="handleEdit(row)">
            <el-icon class="button-icon"><edit-pen /></el-icon>
            编辑
          </el-button>
          <el-button size="small" text type="info" @click="handleDetails(row)">
            <el-icon class="button-icon"><info-filled /></el-icon>
            详情
          </el-button>
          <el-button size="small" text type="danger" @click="handleDelete(row)">
            <el-icon class="button-icon"><delete /></el-icon>
            删除
          </el-button>
        </div>
      </template>
    </table-qvil>

    <!-- 详情弹窗 -->
    <detail-dialog-qvil
      v-model="detailDialogVisible"
      :detail-data="currentDetail || {}"
      :fields="detailFields"
      :loading="false"
      title="入住信息详情"
      @close="handleDetailClose"
    />

    <!-- 表单弹窗 -->
    <form-dialog-qvil
      ref="formDialogRef"
      v-model="dialogState.visible"
      :confirm-loading="dialogState.confirmLoading"
      :error="dialogState.error"
      :fields="formFields"
      :form-data="dialogState.formData"
      :loading="dialogState.loading"
      :title="dialogState.title"
      @cancel="handleFormCancel"
      @confirm="handleConfirmIntercept"
      @validation-error="handleValidationError"
    />

    <!-- 导入组件 -->
    <import-handler ref="importHandlerRef" :activity-id="queryForm.activityId" @error="handleImportError" @success="handleImportSuccess" />
  </div>
</template>

<script lang="ts" setup>
import { Delete, EditPen, InfoFilled } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'
import ImportHandler from './components/ImportHandler.vue'
import {
  detailFields,
  formFields,
  formatFormData,
  getHotelList,
  getHotelName,
  getPlayerList,
  hotelOptions,
  moduleName,
  parseApiData,
  searchFields,
  tableColumns,
  userOptions,
} from './config'
import { addApi, delApi, editApi, getDetailApi, getListApi } from '/@/api/hotelCheckin'

// 查询表单
interface StayInfo {
  id: number
  activityId: string
  userId: string
  hotelManagementId: string
  houseType: string
  houseNumber: string
  dwellStartDate: string
  dwellEndDate: string
  remark: string
  createdAt?: string
  updatedAt?: string
  [key: string]: any
}

interface QueryForm {
  userId: string
  hotelManagementId: string
  houseType: string
  dwellDateRange: string[]
  dwellStartDate: string
  dwellEndDate: string
  activityId: string
  page: number
  limit: number
}

const queryForm = ref<QueryForm>({
  userId: '',
  hotelManagementId: '',
  houseType: '',
  dwellDateRange: [],
  dwellStartDate: '',
  dwellEndDate: '',
  activityId: localStorage.getItem('hongyouActId') || '',
  page: 1,
  limit: 20,
})

// 表格状态
const tableState = reactive({
  data: [] as StayInfo[],
  loading: false,
  pagination: {
    total: 0,
    page: 1,
    pageSize: 20,
  },
  visibleColumns: tableColumns,
})

// 使用对话框状态
const dialogState = reactive({
  visible: false,
  title: `新增${moduleName}`,
  formData: {} as StayInfo,
  loading: false,
  confirmLoading: false,
  error: '',
})

// 详情弹窗相关
const detailDialogVisible = ref(false)
const currentDetail = ref<StayInfo | null>(null)

// 是否为编辑模式
const isEditMode = ref(false)

// 组件引用
const formDialogRef = ref()
const importHandlerRef = ref()

// 获取列表数据
const getList = async () => {
  try {
    tableState.loading = true
    // 构建API请求参数
    const params: Record<string, any> = {
      userId: queryForm.value.userId,
      hotelManagementId: queryForm.value.hotelManagementId,
      houseType: queryForm.value.houseType,
      page: queryForm.value.page,
      limit: queryForm.value.limit,
      activityId: queryForm.value.activityId,
    }

    // 处理日期范围
    if (queryForm.value.dwellDateRange && Array.isArray(queryForm.value.dwellDateRange) && queryForm.value.dwellDateRange.length === 2) {
      params.dwellStartDate = queryForm.value.dwellDateRange[0]
      params.dwellEndDate = queryForm.value.dwellDateRange[1]
    }

    console.log('发送列表请求参数:', params)
    const { result } = await getListApi(params)
    console.log('列表数据返回:', result)

    tableState.data = result.rows.map((item) => parseApiData(item))
    tableState.pagination.total = result.count || 0
    console.log('处理后的表格数据:', tableState.data)
    console.log('分页数据:', tableState.pagination)
  } catch (error) {
    console.error('获取数据异常:', error)
    ElMessage.error('获取数据异常')
    tableState.data = []
    tableState.pagination.total = 0
  } finally {
    tableState.loading = false
  }
}

// 搜索
const handleSearch = () => {
  queryForm.value.page = 1
  getList()
}

// 重置
const handleReset = () => {
  queryForm.value = {
    userId: '',
    hotelManagementId: '',
    houseType: '',
    dwellDateRange: [],
    dwellStartDate: '',
    dwellEndDate: '',
    activityId: localStorage.getItem('hongyouActId') || '',
    page: 1,
    limit: 20,
  }
  getList()
}

// 分页变化
const handlePageChange = (page: number) => {
  console.log('页码变化:', page)
  queryForm.value.page = page
  getList()
}

// 每页条数变化
const handleSizeChange = (size: number) => {
  console.log('每页条数变化:', size)
  queryForm.value.limit = size
  queryForm.value.page = 1
  getList()
}

// 初始化加载
onMounted(() => {
  // 先获取列表数据
  getList()
})

// 处理新增
const handleAdd = () => {
  // 预加载酒店数据
  if (hotelOptions.value.length === 0) {
    getHotelList()
  }

  // 预加载用户数据
  getPlayerList()

  dialogState.error = ''
  isEditMode.value = false
  dialogState.formData = {
    id: 0,
    activityId: queryForm.value.activityId,
    userId: '',
    hotelManagementId: '',
    houseType: '',
    houseNumber: '',
    dwellStartDate: '',
    dwellEndDate: '',
    remark: '',
  } as StayInfo

  dialogState.title = `新增${moduleName}`
  dialogState.visible = true
}

// 处理编辑
const handleEdit = (row: StayInfo) => {
  // 预加载酒店数据
  if (hotelOptions.value.length === 0) {
    getHotelList()
  }

  dialogState.error = ''
  isEditMode.value = true

  try {
    const rowCopy = JSON.parse(JSON.stringify(row))

    // 如果行数据中有userInfo，将其添加到userOptions中确保回显
    if (rowCopy.userInfo && rowCopy.userInfo.id) {
      // 创建用户选项对象
      const userOption = {
        value: String(rowCopy.userInfo.id),
        label: rowCopy.userInfo.name || `用户ID:${rowCopy.userInfo.id}`,
      }

      console.log('从行数据中提取的用户信息:', userOption)

      // 检查是否已经存在相同ID的选项
      const existingOption = userOptions.value.find((opt) => String(opt.value) === String(userOption.value))
      if (!existingOption) {
        // 如果不存在，添加到选项列表中
        userOptions.value.push(userOption)
        console.log('将用户信息添加到选项:', userOptions.value)
      }

      // 修改userId字段，确保表单能够正确回显
      rowCopy.userId = String(rowCopy.userInfo.id)
    }

    dialogState.formData = parseApiData(rowCopy)
    dialogState.title = `编辑${moduleName}`
    dialogState.visible = true
  } catch (error) {
    console.error('处理编辑数据异常:', error)
    ElMessage.error('处理编辑数据异常')
  }
}

// 处理详情
const handleDetails = (row: StayInfo) => {
  try {
    dialogState.loading = true
    getDetailApi(row.id)
      .then(({ result }) => {
        currentDetail.value = parseApiData(result)
        detailDialogVisible.value = true
      })
      .catch((error) => {
        console.error('获取详情异常:', error)
        ElMessage.error('获取详情异常')
      })
      .finally(() => {
        dialogState.loading = false
      })
  } catch (error) {
    console.error('处理详情异常:', error)
    ElMessage.error('处理详情异常')
    dialogState.loading = false
  }
}

// 关闭详情
const handleDetailClose = () => {
  currentDetail.value = null
}

// 处理删除
const handleDelete = (row: StayInfo) => {
  ElMessageBox.confirm(`确定要删除 "${row.houseNumber}" 的入住信息吗？`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        await delApi(row.id)
        ElMessage.success('删除成功')
        getList()
      } catch (error) {
        console.error('删除异常:', error)
        ElMessage.error('删除操作异常')
      }
    })
    .catch(() => {
      // 用户取消删除
    })
}

// 表单提交
const handleFormSubmit = async () => {
  try {
    dialogState.confirmLoading = true
    dialogState.error = ''

    // 检查必填项
    if (!dialogState.formData.userId) {
      ElMessage.error('请选择用户')
      dialogState.error = '请选择用户'
      dialogState.confirmLoading = false
      return
    }

    if (!dialogState.formData.hotelManagementId) {
      ElMessage.error('请选择酒店')
      dialogState.error = '请选择酒店'
      dialogState.confirmLoading = false
      return
    }

    // 已经通过拦截器处理过的数据
    console.log('最终提交的表单数据:', dialogState.formData)

    if (isEditMode.value) {
      const response = await editApi(dialogState.formData)
      if (response.result && response.result.code === -1) {
        ElMessage.error(response.result.message || '编辑失败')
        dialogState.error = response.result.message || '编辑失败'
        return
      }
      ElMessage.success('编辑成功')
    } else {
      const response = await addApi(dialogState.formData)
      console.log('添加接口返回:', response)
      if (response && response.code === -1) {
        ElMessage.error(response.message || '添加失败')
        dialogState.error = response.message || '添加失败'
        return
      }
      ElMessage.success('新增成功')
    }

    dialogState.visible = false
    getList()
  } catch (error: any) {
    console.error(`${isEditMode.value ? '编辑' : '新增'}异常:`, error)
    const errorMsg = error.response?.data?.result?.message || error.message || `${isEditMode.value ? '编辑' : '新增'}操作异常`
    dialogState.error = errorMsg
    ElMessage.error(errorMsg)
  } finally {
    dialogState.confirmLoading = false
  }
}

// 拦截确认事件，处理表单数据
const handleConfirmIntercept = async (formData: any) => {
  try {
    console.log('拦截到的原始表单数据:', formData)

    // 深拷贝表单数据，避免意外修改
    const processedData = JSON.parse(JSON.stringify(formData))

    // 处理userId字段 - 确保是字符串格式
    if (processedData.userId) {
      if (typeof processedData.userId === 'object' && processedData.userId !== null) {
        processedData.userId = String(processedData.userId.value || '')
      } else {
        processedData.userId = String(processedData.userId)
      }
      console.log('处理后的userId:', processedData.userId)
    }

    // 处理hotelManagementId字段 - 确保是字符串格式
    if (processedData.hotelManagementId) {
      if (typeof processedData.hotelManagementId === 'object' && processedData.hotelManagementId !== null) {
        processedData.hotelManagementId = String(processedData.hotelManagementId.value || '')
      } else {
        processedData.hotelManagementId = String(processedData.hotelManagementId)
      }
      console.log('处理后的hotelManagementId:', processedData.hotelManagementId)
    }

    // 使用config.ts中的formatFormData统一处理日期等其他字段
    const formattedData = formatFormData(processedData)
    console.log('最终格式化后的表单数据:', formattedData)

    // 更新dialogState中的formData
    dialogState.formData = formattedData

    // 调用实际的提交函数
    await handleFormSubmit()
  } catch (error) {
    console.error('数据处理异常:', error)
    ElMessage.error('数据处理异常')
    dialogState.confirmLoading = false
  }
}

// 表单取消
const handleFormCancel = () => {
  dialogState.visible = false
}

// 表单验证错误
const handleValidationError = (error: string) => {
  dialogState.error = error
}

// 表单值变化处理
const handleFormChange = () => {
  // 在这里可以添加特殊的表单联动处理逻辑
}

// 打开批量导入
const openImportDialog = () => {
  // 每次打开导入对话框前，先检查并重置其状态
  if (importHandlerRef.value) {
    importHandlerRef.value.resetImportDialog?.()
  }
  importHandlerRef.value?.openImportDialog()
}

// 处理导入成功
const handleImportSuccess = (data: any) => {
  // 统计信息已在组件内处理，此处只需刷新列表

  // 记录导入结果日志
  console.log('入住信息导入完成:', data)

  // 刷新数据列表
  getList()
}

// 处理导入错误
const handleImportError = (error: any) => {
  // 这里不需要重复记录和显示错误信息，主要处理后续逻辑

  // 如果是网络错误，提供重试建议
  if (!navigator.onLine || error.name === 'NetworkError' || error.message?.includes('network')) {
    setTimeout(() => {
      if (navigator.onLine) {
        ElMessage.info('网络已恢复，您可以重新尝试导入操作')
      }
    }, 3000)
  }
}
</script>

<style lang="scss" scoped>
.no-background-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  padding: 0 1.25rem 1.25rem;
  background-color: var(--el-bg-color);
}

.operations-container {
  @apply whitespace-nowrap flex gap-2;
}

.button-icon {
  @apply mr-1 align-middle;
}
</style>
